﻿using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Web.Hosting;

namespace Core.Library
{
    public class Logging
    {
        private const string FromPassword = "12345!@#$%";
        private const string FromAddress = "errorlog.quiz@gmail.com";
        private const string Host = "smtp.gmail.com";
        private const int Port = 587;
        private const string MapPath = "/Data/Logging/";

        public static void TextLog(string message)
        {
            var path = MapPath + DateTime.Now.Year + DateTime.Now.Month + "/";
            path = HostingEnvironment.MapPath(path);
            var dir = new DirectoryInfo(path);
            if(!dir.Exists)
                dir.Create();

            var fileName = DateTime.Now.Day + ".txt";
            using (StreamWriter sw = File.AppendText(path + fileName))
            {
                sw.WriteLine(DateTime.Now + " - " + message);
            }
        }

        public static void SendMail(string receiver, string[] cc, string subject, string body, Attachment attachment)
        {
            MailAddress fromAddress = new MailAddress(FromAddress);
            MailAddress toAddress = new MailAddress(receiver);

            SmtpClient smtp = new SmtpClient(Host, Port);
            smtp.EnableSsl = true;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(fromAddress.Address, FromPassword);

            MailMessage mailMsg = new MailMessage(fromAddress, toAddress);
            if (cc != null && cc.Length > 0)
            {
                foreach (string s in cc)
                {
                    mailMsg.Bcc.Add(s);
                }
            }
            mailMsg.Subject = subject;
            mailMsg.Body = body;
            if (attachment != null)
            {
                mailMsg.Attachments.Add(attachment);
            }
            mailMsg.IsBodyHtml = true;
            smtp.Send(mailMsg);

        }
    }
}